package com.example.cmh.service.impl;

import com.example.cmh.common.CustomException;
import com.example.cmh.common.PageResult;
import com.example.cmh.common.Result;
import com.example.cmh.mapper.MeetingMapper;
import com.example.cmh.pojo.Meeting;
import com.example.cmh.service.MeetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class MeetingServiceImpl implements MeetingService {

    @Autowired
    private MeetingMapper meetingMapper;

    @Override
    @Transactional
    public Result<String> createMeeting(Meeting meeting, Integer currentUserId) throws CustomException {
        try {
            // 基本验证
            if (meeting.getMeetingName() == null || meeting.getMeetingName().trim().isEmpty()) {
                throw new CustomException("会议名称不能为空");
            }
            if (meeting.getStartTime() == null) {
                throw new CustomException("开始时间不能为空");
            }
            if (meeting.getEndTime() == null) {
                throw new CustomException("结束时间不能为空");
            }
            if (meeting.getStartTime().after(meeting.getEndTime())) {
                throw new CustomException("开始时间不能晚于结束时间");
            }
            
            // 设置创建者ID
            meeting.setCreatPersonId(currentUserId);
            
            // 根据创建者ID设置审核状态
            if (currentUserId != null && currentUserId == 1) {
                // 管理员创建的会议直接设置为已审核
                meeting.setMeetingStatus(1);
            } else {
                // 普通用户创建的会议设置为未审核
                meeting.setMeetingStatus(0);
            }
            
            int result = meetingMapper.insert(meeting);
            if (result > 0) {
                return Result.success("创建会议成功", "success");
            } else {
                throw new CustomException("创建会议失败");
            }
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            throw new CustomException("创建会议时发生错误: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> updateMeeting(Boolean isAdmin, Meeting meeting) throws CustomException {
        try {
            // 基本验证
            if (meeting.getMeetingId() == null) {
                throw new CustomException("会议ID不能为空");
            }
            if (meeting.getMeetingName() == null || meeting.getMeetingName().trim().isEmpty()) {
                throw new CustomException("会议名称不能为空");
            }
            if (meeting.getStartTime() != null && meeting.getEndTime() != null) {
                if (meeting.getStartTime().after(meeting.getEndTime())) {
                    throw new CustomException("开始时间不能晚于结束时间");
                }
            }
            
            // 检查会议是否存在
            Meeting existingMeeting = meetingMapper.selectById(meeting.getMeetingId());
            if (existingMeeting == null) {
                throw new CustomException("会议不存在");
            }
            if(isAdmin){
                meeting.setMeetingStatus(1);
            }
            else meeting.setMeetingStatus(0);

            int result = meetingMapper.updateById(meeting);
            if (result > 0) {
                return Result.success("更新会议成功", "success");
            } else {
                throw new CustomException("更新会议失败");
            }
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            throw new CustomException("更新会议时发生错误: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> deleteMeeting(Integer meetingId) throws CustomException {
        try {
            if (meetingId == null) {
                throw new CustomException("会议ID不能为空");
            }
            
            // 检查会议是否存在
            Meeting existingMeeting = meetingMapper.selectById(meetingId);
            if (existingMeeting == null) {
                throw new CustomException("会议不存在");
            }
            
            int result = meetingMapper.deleteById(meetingId);
            if (result > 0) {
                return Result.success("删除会议成功", "success");
            } else {
                throw new CustomException("删除会议失败");
            }
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            throw new CustomException("删除会议时发生错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Meeting>> getMeetingList(String meetingName, String creatPerson, Date startTime, Integer currentUserId) throws CustomException {
        try {
            // 根据用户权限过滤会议
            Integer meetingStatus = null;
            Integer creatPersonId = null;
            
            if (currentUserId != null && currentUserId == 1) {
                // 管理员可以看到所有会议
                meetingStatus = null;
                creatPersonId = null;
            } else if (currentUserId != null) {
                // 普通用户只能看到已审核的会议和自己的未审核会议
                meetingStatus = 1; // 显示已审核的会议
                creatPersonId = currentUserId; // 同时显示自己创建的未审核会议
            } else {
                // 如果没有用户ID，只显示已审核的会议
                meetingStatus = 1;
                creatPersonId = null;
            }
            
            List<Meeting> meetings = meetingMapper.selectMeetings(meetingName, creatPerson, startTime, meetingStatus, creatPersonId);
            return Result.success(meetings);
        } catch (Exception e) {
            throw new CustomException("获取会议列表时发生错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Meeting>> getAllMeetings(String meetingName, String creatPerson, Date startTime) throws CustomException {
        try {
            // 调试接口：查看所有会议，不受权限限制
            List<Meeting> meetings = meetingMapper.selectMeetings(meetingName, creatPerson, startTime, null, null);
            return Result.success(meetings);
        } catch (Exception e) {
            throw new CustomException("获取所有会议列表时发生错误: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> reviewMeeting(Integer meetingId, Integer status) throws CustomException {
        try {
            if (meetingId == null) {
                throw new CustomException("会议ID不能为空");
            }
            if (status == null || (status != 1 && status != 2)) {
                throw new CustomException("审核状态无效，1表示通过，2表示拒绝");
            }
            
            // 检查会议是否存在
            Meeting existingMeeting = meetingMapper.selectById(meetingId);
            if (existingMeeting == null) {
                throw new CustomException("会议不存在");
            }
            
            int result = meetingMapper.updateMeetingStatus(meetingId, status);
            if (result > 0) {
                String message = status == 1 ? "审核通过成功" : "审核拒绝成功";
                return Result.success(message, "success");
            } else {
                throw new CustomException("审核操作失败");
            }
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            throw new CustomException("审核会议时发生错误: " + e.getMessage());
        }
    }

    @Override
    public Result<PageResult<Meeting>> getMeetingListWithPage(String meetingName, String creatPerson, Date startTime, 
                                                             Integer currentUserId, Integer current) throws CustomException {
        try {
            // 参数验证和默认值设置
            if (current == null || current < 1) {
                current = 1;
            }
            
            // 固定每页10条数据
            int size = 10;
            
            // 计算偏移量
            int offset = (current - 1) * size;
            
            // 根据用户权限过滤会议
            Integer meetingStatus = null;
            Integer creatPersonId = null;
            
            if (currentUserId != null && currentUserId == 1) {
                // 管理员可以看到所有会议
                meetingStatus = null;
                creatPersonId = null;
            } else if (currentUserId != null) {
                // 普通用户只能看到已审核的会议和自己的未审核会议
                meetingStatus = 1; // 显示已审核的会议
                creatPersonId = currentUserId; // 同时显示自己创建的未审核会议
            } else {
                // 如果没有用户ID，只显示已审核的会议
                meetingStatus = 1;
                creatPersonId = null;
            }
            
            // 查询总数
            long total = meetingMapper.countMeetings(meetingName, creatPerson, startTime, meetingStatus, creatPersonId);
            
            // 查询分页数据
            List<Meeting> meetings = meetingMapper.selectMeetingsWithPage(meetingName, creatPerson, startTime, 
                                                                         meetingStatus, creatPersonId, offset, size);
            
            // 创建分页结果
            PageResult<Meeting> pageResult = new PageResult<>(meetings, total, current, size);
            
            return Result.success(pageResult);
        } catch (Exception e) {
            throw new CustomException("获取分页会议列表时发生错误: " + e.getMessage());
        }
    }
} 